package com.getpebble.android.framework.analytics;

import android.app.IntentService;
import android.content.Intent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.getpebble.android.Features;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.AnalyticsLogger;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.config.BootConfig;
import com.getpebble.android.framework.datalogging.Datalogging;
import com.getpebble.android.framework.protocol.inbound.PblInboundDataloggingMessage.Datatype;
import com.google.common.primitives.UnsignedInteger;
import com.sun.mail.imap.IMAPStore;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TimeZone;
import java.util.UUID;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class WatchAnalytics extends IntentService {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    private static final String TAG = WatchAnalytics.class.getSimpleName();
    public static final UUID WATCH_ANALYTICS_APP_UUID = new UUID(0, 0);
    public static final UnsignedInteger WATCH_ANALYTICS_TAG = UnsignedInteger.fromIntBits(78);
    private static final Random mRandom = new Random();
    private long mLastDelayTime = 0;

    static {
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    }

    public WatchAnalytics() {
        super("WatchAnalytics");
    }

    public void onHandleIntent(Intent intent) {
        try {
            int dataId = getDataIdFrom(intent);
            String rawAnalyticsData = getRawAnalyticsDataFrom(intent);
            UUID logUuid = getUuidFrom(intent);
            try {
                if (Features.getWatchAnalytics().isOn() && AnalyticsLogger.isActive()) {
                    desynchronizeMessageTiming();
                    if (submitServerRequest(assembleJsonData(rawAnalyticsData))) {
                        sendWatchAnalyticsAck(dataId, logUuid);
                        return;
                    }
                    return;
                }
                sendWatchAnalyticsAck(dataId, logUuid);
            } catch (JsonProcessingException e) {
                Trace.info(TAG, "unable to generate JSON for watch analytics", e);
            } catch (IOException e2) {
                Trace.info(TAG, "IOException during watch analytics submission", e2);
            } catch (RuntimeException e3) {
                Trace.info(TAG, "unexpected exception processing watch analytics", e3);
            }
        } catch (IllegalArgumentException e4) {
            Trace.info(TAG, "missing or invalid data from intent", e4);
        } catch (ClassCastException e5) {
            Trace.info(TAG, "unexpected data type found while parsing intent", e5);
        } catch (RuntimeException e32) {
            Trace.info(TAG, "unexpected exception while parsing intent", e32);
        }
    }

    private static int getDataIdFrom(Intent intent) throws IllegalArgumentException {
        int dataId = intent.getIntExtra("pbl_data_id", -1);
        if (dataId >= 0) {
            return dataId;
        }
        throw new IllegalArgumentException("Invalid data id");
    }

    private static String getRawAnalyticsDataFrom(Intent intent) {
        byte dataTypeCode = intent.getByteExtra("pbl_data_type", (byte) -1);
        Datatype dataType = Datatype.fromCode(dataTypeCode);
        if (dataType != null && Datatype.BYTE_ARRAY.equals(dataType)) {
            return intent.getStringExtra("pbl_data_object");
        }
        throw new IllegalArgumentException("Invalid data type: " + dataTypeCode);
    }

    private static UUID getUuidFrom(Intent intent) {
        return (UUID) intent.getSerializableExtra("data_log_uuid");
    }

    private void desynchronizeMessageTiming() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - this.mLastDelayTime >= 1800000) {
            this.mLastDelayTime = currentTime;
            int delay = mRandom.nextInt(60000);
            if (delay > 0) {
                try {
                    Trace.verbose(TAG, "desynchronizeMessageTiming start: " + delay);
                    Thread.sleep((long) delay);
                    Trace.verbose(TAG, "desynchronizeMessageTiming finished");
                } catch (InterruptedException e) {
                    Trace.info(TAG, "Interrupted", e);
                }
            }
        }
    }

    private String assembleJsonData(String rawAnalyticsData) throws JsonProcessingException {
        Map<String, Object> globalProperties = AnalyticsLogger.getStaticGlobalProperties();
        TimeZone timeZone = TimeZone.getDefault();
        Map<String, Object> topLevel = new HashMap();
        topLevel.put("tz_offset", Integer.valueOf(timeZone.getRawOffset() / IMAPStore.RESPONSE));
        topLevel.put("global_properties", globalProperties);
        topLevel.put("analytics_data", rawAnalyticsData);
        return MAPPER.writeValueAsString(topLevel);
    }

    private boolean submitServerRequest(String jsonData) throws IOException {
        BootConfig bootconfig = BootConfig.createInstance(getApplicationContext());
        if (bootconfig == null) {
            Trace.info(TAG, "Bootconfig is null");
            return false;
        }
        String urlAsString = bootconfig.getRemoteDeviceAnalytics();
        if (urlAsString == null) {
            Trace.info(TAG, "url is null");
            return false;
        }
        HttpPost httpPost = new HttpPost(urlAsString);
        httpPost.setHeader("Content-Type", "application/json");
        if (new PblPreferences(getApplicationContext()).getBooleanData(PrefKey.DATALOGGING_DEBUG, false)) {
            Trace.verbose(TAG, "Sending watch analytics to server: '" + jsonData + "'");
        }
        StringEntity requestEntity = new StringEntity(jsonData, "utf-8");
        httpPost.setEntity(requestEntity);
        int statusCode = new DefaultHttpClient().execute(httpPost).getStatusLine().getStatusCode();
        if (200 <= statusCode && statusCode < 300) {
            Trace.verbose(TAG, "successful watch analytics");
            return true;
        } else if (statusCode == 400) {
            Trace.info(TAG, "server rejected watch analytics data, will purge message");
            Map<String, Object> dataFields = new HashMap();
            dataFields.put("data", requestEntity);
            MobileAppBehavior.logWatchAnalyticsUploadRejectedEvent(dataFields);
            return true;
        } else {
            Trace.info(TAG, "watch analytics server failed with status " + statusCode);
            return false;
        }
    }

    private void sendWatchAnalyticsAck(int dataId, UUID logUuid) {
        Datalogging.getInstance(getApplicationContext()).handleClientAck(logUuid, dataId);
    }
}
